#include "ball.h"
#include <QPainter>

Ball::Ball(qreal radius, qreal posX, qreal posY) :
    QGraphicsItem(), m_radius(radius)
{
    setPos(posX, posY);
    setFlag(QGraphicsItem::ItemIsMovable, true);
}

QRectF Ball::boundingRect() const
{
    const qreal penWidth = 1;
    const qreal diameter = 2 * m_radius;
    return QRectF(pos().rx() - m_radius - penWidth / 2,
                  pos().ry() - m_radius - penWidth / 2,
                  diameter + penWidth,
                  diameter + penWidth);
}

void Ball::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QBrush brush(Qt::blue);
    QPen pen;

    QList<QGraphicsItem*> collidingItemsList = collidingItems();
    if (!collidingItemsList.isEmpty())
    {
        brush.setColor(Qt::red);
    }
    for (QGraphicsItem *item : collidingItemsList)
    {
        item->update();
    }

    brush.setStyle(Qt::Dense6Pattern);
    pen.setStyle(Qt::DashLine);
    painter->setBrush(brush);
    painter->setPen(pen);
    painter->drawRect(boundingRect());

    brush.setStyle(Qt::SolidPattern);
    pen.setStyle(Qt::SolidLine);
    painter->setBrush(brush);
    painter->setPen(pen);
    painter->drawEllipse(boundingRect());
}

QPainterPath Ball::shape() const
{
    QPainterPath path;
    path.addEllipse(boundingRect());
    return path;
}
